package com.itheima.web.controller.system.user;

import com.github.pagehelper.PageInfo;
import com.itheima.domain.system.Dept;
import com.itheima.domain.system.Module;
import com.itheima.domain.system.Role;
import com.itheima.domain.system.User;
import com.itheima.utils.BeanUtil;
import com.itheima.web.controller.BaseServlet;
import org.apache.commons.lang3.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @program: mm
 * @description:
 * @author: zhanghz001
 * @create: 2020-11-12 15:37
 **/
@WebServlet("/system/user")
public class UserServlet extends BaseServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String operation = req.getParameter("operation");
        if ("list".equals(operation)) {
            list(req, resp);
        } else if ("save".equals(operation)) {
            save(req, resp);
        } else if ("delete".equals(operation)) {
            delete(req, resp);
        } else if ("edit".equals(operation)) {
            edit(req, resp);
        } else if ("toAdd".equals(operation)) {
            toAdd(req, resp);
        } else if ("toEdit".equals(operation)) {
            toEdit(req, resp);
        } else if ("updateRole".equals(operation)) {
            this.updateRole(req, resp);
        } else if ("userRoleList".equals(operation)) {
            userRoleList(req, resp);
        } else if ("logout".equals(operation)) {
            logout(req, resp);
        } else if ("home".equals(operation)) {
            home(req, resp);
        } else if ("login".equals(operation)) {
            login(req, resp);
        } else {
            System.out.println("没有定义的url");
        }
    }

    private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.getSession().invalidate();
        resp.sendRedirect(req.getContextPath() + "/login.jsp");
    }

    private void home(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        req.getRequestDispatcher("/WEB-INF/pages/home/home.jsp").forward(req, resp);
    }

    private void login(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        String email = req.getParameter("email");
        String password = req.getParameter("password");
        User user = userService.login(email, password);
        if (user == null) {
            req.setAttribute("error", "账号或者密码不存在");
            req.getRequestDispatcher("/login.jsp").forward(req, resp);
            // resp.sendRedirect(req.getContextPath() + "/login.jsp");
        } else {
            req.getSession().setAttribute("user", user);

            //如果登录成功，加载该用户对应的角色对应的所有模块
            List<Module> moduleList = userService.findModuleById(user.getId());
            //
            req.getSession().setAttribute("modules", moduleList);

            //当前登录用户对应的可操作模块的所有url拼接成一个大的字符串
            StringBuffer sbf = new StringBuffer();
            for (Module m : moduleList) {
                sbf.append(m.getCurl());
                sbf.append(',');
            }
            req.getSession().setAttribute("authorStr", sbf.toString());
            //跳转页面
            req.getRequestDispatcher("/WEB-INF/pages/home/main.jsp").forward(req, resp);

        }
    }

    private void updateRole(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String userId = request.getParameter("userId");
        String[] roleIds = request.getParameterValues("roleIds");
        userService.updateRole(userId, roleIds);
        //跳转回到页面list
        response.sendRedirect(request.getContextPath() + "/system/user?operation=list");
    }

    private void userRoleList(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String userId = req.getParameter("id");
        User user = userService.findById(userId);
        req.setAttribute("user", user);
        List<Role> all = roleService.findAllRoleByUserId(userId);
        req.setAttribute("roleList", all);
        req.getRequestDispatcher("/WEB-INF/pages/system/user/role.jsp").forward(req, resp);
    }

    private void toEdit(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        String id = req.getParameter("id");
        User user = userService.findById(id);
        req.setAttribute("user", user);
        List<Dept> all = deptService.findAll();
        req.setAttribute("deptList", all);

        req.getRequestDispatcher("/WEB-INF/pages/system/user/update.jsp").forward(req, resp);

    }

    private void toAdd(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        List<Dept> all = deptService.findAll();
        req.setAttribute("deptList", all);
        req.getRequestDispatcher("/WEB-INF/pages/system/user/add.jsp").forward(req, resp);

    }

    private void edit(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = BeanUtil.fillBean(req, User.class, "yyyy-MM-dd");

        userService.update(user);
        resp.sendRedirect(req.getContextPath() + "/system/user?operation=list");

    }

    private void delete(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = BeanUtil.fillBean(req, User.class);
        userService.delete(user);
        resp.sendRedirect(req.getContextPath() + "/system/user?operation=list");

    }

    private void save(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        User user = BeanUtil.fillBean(req, User.class, "yyyy-MM-dd");
        userService.save(user);
        resp.sendRedirect(req.getContextPath() + "/system/user?operation=list");

    }

    private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String pageStr = req.getParameter("page");
        String sizeStr = req.getParameter("size");

        int page = 1;
        int size = 10;
        if (StringUtils.isNotBlank(pageStr)) {
            try {
                page = Integer.parseInt(pageStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (StringUtils.isNotBlank(sizeStr)) {
            try {
                size = Integer.parseInt(sizeStr);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        PageInfo pageInfo = userService.findAll(page, size);
        req.setAttribute("page", pageInfo);
        //转发不需要带上ctx
        req.getRequestDispatcher("/WEB-INF/pages/system/user/list.jsp").forward(req, resp);

    }
}
